<?php
class model_newagk_units extends gdl_components_basemodel 
{

    public function primarykey() {
        return 'id';
    }

    public function tableName() {
        return 'agk_units';
    }
	public function getInfoArg($arrg=[],$field)
    {
		if(empty($arrg)) return false;
		return $this->select($arrg, $field)->items;
    }
	
	/*权限列表
	*$admin string zg总管理员 gl单位管理员其他的暂定
	*platformid int 平台id
	*unitid 部门id
	*
	*/
	 public function getMenu($admin='gl',$platformid,$unitid=0)

    {
		$adminuser = new model_newagk_adminuser();
		$unitArr = $adminuser->select(['platform_id'=>$platformid], 'unitid,count(*) num','group by unitid  order by unitid desc')->items;
		$nodes = $this->getInfoArg(['platform_id'=>$platformid,'status'=>1,'isdelete'=>1],"id,parentid,unit_name,status,level"); //获取当前平台所有架构
		$list = [];
		if($admin=='zg'){
			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentid'],
						'name'=>$v['unit_name'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>1, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
						if(!empty($list[$v['parentid']])){
							$list[$v['parentid']]['hasChildren']=1;
						}
			}
		} else {
			$Checks_yes = $this->operating($platformid,$unitid=0);
			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentid'],
						'name'=>$v['unit_name'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>in_array($v['id'],$Checks_yes) ? 1 : 2, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
				if(!empty($list[$v['parentid']])){
					$list[$v['parentid']]['hasChildren']=1;
				}
			}
		}
		/****写入每个部门人数*****/
		foreach($unitArr as $vu){
			$id = empty($list[$list[$vu['unitid']]['pid']]) ? 0 : $list[$vu['unitid']]['pid'];
			//$list[$vu['unitid']]['num'] = $vu['num']; //分别显示每个组人数的就用这个
			$list[$vu['unitid']]['num'] += $vu['num'];
			if(!empty($list[$list[$vu['unitid']]['pid']])){
				$list[$id]['num'] += $vu['num'];
			}
		}
		/****写入每个部门人数 end*****/
		return $list;
    }
	
	/*权限列表【不显示所有列表】
	*$admin string zg总管理员 gl单位管理员其他的暂定
	*platformid int 平台id
	*unitid 部门id
	*
	*/
	public function getMenuSpecial($admin='gl',$platformid,$unitid=0,$title='')

    {
		$platformid = intval($platformid);
		$adminuser = new model_newagk_adminuser();
		$unitArr = $adminuser->select(['platform_id'=>$platformid], 'unitid,count(*) num','group by unitid  order by unitid desc')->items;
		 //获取当前平台所有架构
		$list = [];
		$condition = 'platform_id='.$platformid.' and isdelete=1';
		$searchs = [0];
		
		
		if($admin=='zg'){
			if($title!=''){
				$searchs = $this->searchs($title,$platformid);
				$condition.=' and id in('.implode(',',$searchs).')';
			}
			
			$nodes = $this->getInfoArg($condition,"id,parentid,unit_name,status,level");
			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentid'],
						'title'=>$v['unit_name'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>1, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
						if(!empty($list[$v['parentid']])){
							$list[$v['parentid']]['hasChildren']=1;
						}
			}
		} else {
			$Checks_yes = $this->operating($platformid,$unitid);
			$getSuperior = $this->getSuperior($platformid,$unitid);
			$currentId = array_merge($Checks_yes,$getSuperior);
			if($title!=''){
				$searchs = $this->searchs($title,$platformid,$currentId);
				$condition.=' and id in('.implode(',',$searchs).')';
			} else {
				$condition.=' and id in('.implode(',',$currentId).')';
			}
			$nodes = $this->getInfoArg($condition,"id,parentid,unit_name,status,level");

			foreach($nodes as $v){
				$list[$v['id']] = [
						'id'=>$v['id'],
						'pid'=>$v['parentid'],
						'title'=>$v['unit_name'],
						'status'=>$v['status'],
						'level'=>$v['level'],
						'operat'=>in_array($v['id'],$Checks_yes) ? 1 : 2, //是否可操作1是可以 2是不可以
						'hasChildren'=>2, //1表示有子数组 2表示没有
						'num'=>0,//人数
						];
				if(!empty($list[$v['parentid']])){
					$list[$v['parentid']]['hasChildren']=1;
				}
			}
		}
		/****写入每个部门人数*****/
		foreach($unitArr as $vu){
			$id = empty($list[$list[$vu['unitid']]['pid']]) ? 0 : $list[$vu['unitid']]['pid'];
			//$list[$vu['unitid']]['num'] = $vu['num']; //分别显示每个组人数的就用这个
			if(!empty($list[$vu['unitid']])){
			$list[$vu['unitid']]['num'] += $vu['num'];
				if(!empty($list[$list[$vu['unitid']]['pid']])){
					$list[$id]['num'] += $vu['num'];
				}
			}
		}
		/****写入每个部门人数 end*****/
		return $list;
    }
	
	
	
	/*获取用户可操作单位id
	*platformid int 平台id
	*unitid 部门id
	*
	*/
	public function operating($platformid,$unitid=0)
	{
		$nodes = $this->selectOne(['platform_id'=>$platformid,'isdelete'=>1,'id'=>$unitid],"level,id");
		$list = [0];
		if(empty($nodes)) return $list;
		$list[] = $nodes['id'];
		$level = $this->getInfoArg("platform_id='{$platformid}' and isdelete=1 and level>".$nodes['level'],"id,parentid",'order by level asc'); //获取低于当前层级的数据
		foreach($level as $v){
			if(in_array($v['parentid'],$list)){
				$list[] = $v['id']; //获取当前用户可操作单位id
			}
		}
		
		return $list;
    }
	
	/*获取所有部门id，name
	*platformid int 平台id
	*
	*
	*/
	public function unitsDetails($platformid,$units_id)
	{			

				$list = [];
				if(empty($units_id)) return $list;
				$units_name = $this->getInfoArg('platform_id='.$platformid.' and id in('.implode(',',$units_id ).')','id,name');
				foreach($adminunits as $v){
					$list[$v['id']] = $v['name'];
				}
		
				return $list;
    }
	
	/*获取所有部门id
	*platformid int 平台id

	*
	*/
	public function adminunits($platformid)
	{			
				$list = [0];
				$condition = ['platform_id'=>$platformid,'status'=>1,'isdelete'=>1];
				$adminunits = $this->select($condition,'id')->items;
				foreach($adminunits as $v){
					$list[] = $v['id'];
				}
		
		return $list;
    }
	
	/*获取当前用户所有上级id
	*platformid int 平台id
	*unitid 部门id
	*
	*/
	public function getSuperior($platformid,$unitid=0)
	{
		$nodes = $this->selectOne(['platform_id'=>$platformid,'isdelete'=>1,'id'=>$unitid],"level,id,parentid");
		$list = [0];
		if(empty($nodes)) return $list;
		$list[] = $nodes['id'];
		$pid[] = $nodes['parentid'];
		$level = $this->getInfoArg("platform_id='{$platformid}'  and isdelete=1 and level<=".$nodes['level'],"id,parentid",'order by level asc'); //获取低于当前层级的数据
		foreach($level as $v){
			if(in_array($v['id'],$pid)){
				$list[] = $v['id']; //获取当前用户可操作单位id
				$pid[] = $v['parentid'];
			}
		}
		
		return $list;
    }
	
	//获取能操作的部门
	public function enabled($userid,$reg,$unitid=0)
	{
		
		$adminuser = new model_newagk_adminuser();
		$admin = $adminuser->selectOne(['id'=>$userid,'reg'=>$reg],'id,characters,platform_id,unitid');
			if(empty($admin['id'])){
				$data = ['code'=>'n','msg'=>'帐号错误','mark'=>[]];
				return $data;
			}
			
			if($admin['characters']!='zg'){ //非平台管理员需要检查权限
			$operating = $this->operating($admin['platform_id'],$admin['unitid']);
				if(!in_array($unitid,$operating)){
					$result->message = '没有修改权限';
					
					$data = ['code'=>'n','msg'=>'没有修改权限','mark'=>[]];
					return $data;
				}
			}
		return ['code'=>'y','msg'=>'可以操作','mark'=>$admin];
    }
	
	
	
	/*获取用户可操作单位id
	*platformid int 平台id
	*datas 操作的部门集合
	*
	*/
	public function depart($datas,$platformid,$userid,$pid=0,$level=0)
	{
		$globas = new service_globals();
		$adminrole = new model_newagk_adminrole();
		$pinyin = new service_pinyin();

		$datime = time();
		try {
			foreach($datas as $v){
				$v['name'] = $globas->getStr($v['name']);
				if($v['id']){ //修改
					$id= intval($v['id']);
					$data = [
							'name'=>$pinyin->getFirstPY($v['name']),
							'unit_name'=> $v['name'],//'单位名',
							'updateTime'=> $datime,//'更新时间',
							];
					
					$this->update(['id' => $id],$data);
					usleep(100);
				} else if(!empty($v['name'])){ //添加
					$names = $pinyin->getFirstPY($v['name']);
					$reg = $globas->get_random().$names;
					$data = [
							'name'=>$names,
							'platform_id'=>$platformid,
							'parentid'=>$pid,//'上级单位id',
							'unit_name'=> $v['name'],//'单位名',
							'createTime'=> $datime,//'单位创建时间',
							'updateTime'=> $datime,//'更新时间',
							'admin_reg'=> $reg,//'单位标记',
							'level'=> $level,//'第几级（暂定）',
							'userid'=>$userid,
							];
					$id = $this->insert($data);
					$adminrole->insert([
						'changes'=> 1,
						'name'=> 'Administrator',//'名称',
						'platform_id'=> $platformid,//'平台ID',
						'isdelete'=> 1,
						'create_time'=> $datime,//'添加时间',
						'update_time'=> $datime,//'更新时间',
						'units'=> $id,//'单位iid',
						'admin_reg'=>$reg,
						'status'=>$v['status'],
					]);
					usleep(100);
				}
				if(!empty($v['child']) && is_array($v['child'])){
					self::depart($v['child'],$platformid,$userid,$id,($level+1));
				}
			}
		} catch (Exception $e) {

        }
		
		return true;
    }
	//获取指定平台下所有单位
	public function getLIst($platform_id=0)
    {
		if(!$platform_id) return false;
		$res = $this->select(['platform_id'=>$platform_id,'status'=>1,'isdelete'=>1],'id,unit_name,parentid')->items;
		
		return $res;
    }
	
	//获取可以操作的单位名
	public function managements($list=[],$userid,$platform_id)
    {
		if(empty($list)) return [];
		$adminroleuser = new model_newagk_adminroleuser();
		$adminrole = new model_newagk_adminrole();
		
		$unitid = $adminroleuser->select(['user_id'=>$userid],'unitid')->items;
		$role = $adminrole->getLIstadmin($platform_id);
		$unitidList = [];
		foreach($unitid as $v){ //获取当前管理员所在的单位
			$unitidList[] = $v['unitid'];
		}
		
		$res = [];
		foreach($list as $vl){
			if(in_array($vl['parentid'],$unitidList)){
				$unitidList[] = $vl['id'];
				$res[] = [
							'id'=>$vl['id'],
							'title'=>$vl['unit_name'],
							'groupsid'=>empty($role[$vl['id']]) ? 0 : $role[$vl['id']],
							];
				
			}
		}
		
		
		return $res;
    }
	function searchs($title='',$platformid,$id=[]){
			$searchs = [0];
			$condition = "unit_name like '%{$title}%' and platform_id=".$platformid;
			if(!empty($id)){
				$condition .= ' and id in ('.implode(',',$id).')';
			}
			$unit_sr_id = $this->getInfoArg($condition,'id');
			foreach($unit_sr_id as $v){
				$Checks_yes = $this->operating($platformid,$v['id']);
				$getSuperior = $this->getSuperior($platformid,$v['id']);
				usleep(100); //所谓的预留后面大优化 (*^_^*)
				$searchs = array_merge($searchs,$Checks_yes);
				$searchs = array_merge($searchs,$getSuperior);
			}
			
		return $searchs;
	}
	
}
